/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
        vector<vector<int>> res;
        if (!root)
            return res;
        vector<TreeNode*> q(2001);
        int l = 0, r = 0;
        q[r++] = root;
        bool reverse = false;
        while (l < r)
        {
            int sz = r - l;
            vector<int> ans;
            for (int i = reverse ? r - 1 : l, j = reverse ? -1 : 1, k = 0; k < sz; i += j, k++)
            {
                TreeNode* cur = q[i];
                ans.push_back(cur->val);
            }
            for (int i = 0; i < sz; i++)
            {
                TreeNode* cur = q[l++];

                if (cur->left)
                    q[r++] = cur->left;
                if (cur->right)
                    q[r++] = cur->right;
            }
            res.push_back(ans);
            reverse = !reverse;
        }
        return res;
    }
};
